var express = require('express');
var router = express.Router();
var codeDB = require('../models/code_datas');
var userDB = require('../models/users_datas');
var problemDB = require('../models/problem_datas');
var mongoose = require('mongoose')
/* GET users listing. */
router.get('/', function(req, res, next) {
    doc=req.session.user
    if(doc){ 
        userDB.findOne({username:doc.username},function(err,data){
            if(err){
                res.json({
                    status:'500',
                    msg:err.message,
                    result:{}
                })
            }
            else
            {
                res.json({
                    status:'1',
                    msg:'',
                    result:{
                        username:data.username,
                        status:data.status,
                        intro:data.intro,
                        gender:data.gender
                    }
                })
            }
        })
    }
    else{
        res.json({
            status:'2',
            msg:'用户未登录',
            result:{}
        })
    }
});
//
router.post('/',function(req,res,next){
    doc=req.session.user
    if(doc){
        let param={
            intro:req.body.intro,
            gender:req.body.gender
        }
        userDB.findOneAndUpdate({username:doc.username},param,function(err,data){
            if(err){
                res.json({
                    status:'0',
                    msg:err.message,
                    result:{}
                })
            }
            else{
                res.json({
                    status:'1',
                    msg:'修改成功',
                    result:{}
                })
            }
        })

    }
    else{
        res.json({
            status:'2',
            msg:'用户未登录',
            result:{}
        })
    }
})


router.get('/problemdone',function (req, res, next) {
  if(req.session.user){
      var uid=req.session.user._id
      codeDB.aggregate([{
        $match:{
            user_id:mongoose.Types.ObjectId(uid)
          },   
      },
      {
        $lookup: {
            from: "problems",
            localField: "problem_id",
            foreignField: "_id",
            as: "problem"
        }
    },
    {
        $project:{
            _id:0,
            modify_time:1,
            problem:1
        }
    },
    {
        $sort:{
            modify_time:-1
          }
      }],function(err,data){
        if(err){
            res.json({
                status: '500',
                msg: err.message,
                result: {}
            });
        }
        else{
            res.json({
                status: '1',
                msg: '',
                result: {
                    problemSet:data,
                }
            });
        }
      })
     
  }else{
      res.json({
          status: "2",
          msg: 'Insufficient permission',
          result: {}
      });
  }
})

module.exports = router;
